import { Inject, Provide, Singleton } from '@midwayjs/core';
import * as NodeRSA from 'node-rsa'
import { RedisService } from '@midwayjs/redis'
// import { BaseError as R } from './base.error'
import * as bcrypt from 'bcryptjs'
import { BECRYPT_SALT } from '../config';

@Provide()
@Singleton()
export class RSAService {

  @Inject()
  redisService: RedisService

  /** 获取公钥 */
  async getPublicKey(): Promise<string> {
    const key = new NodeRSA({ b: 512 });
    const publicKey = key.exportKey('public');
    const privateKey = key.exportKey('private');
    await this.redisService.set(`publicKey: ${publicKey}`, privateKey);
    return publicKey;
  }

  /** 解密 */
  async decrypt(publicKey: string, data: string): Promise<string> {
    const privateKey = await this.redisService.get(`publicKey: ${publicKey}`);

    // 解密
    const rsaDecrypt = new NodeRSA(privateKey);
    rsaDecrypt.setOptions({ encryptionScheme: 'pkcs1' });
    return rsaDecrypt.decrypt(data, 'utf8');
  }

  /** 对比 */
  compareStr(str: string, hashStr: string) {
    return bcrypt.compareSync(str, hashStr);
  }

  encryptStr(str: string) {
    const salt = bcrypt.genSaltSync(BECRYPT_SALT);
    return bcrypt.hashSync(str, salt);
  }

  /** 哈希加密 */
  encryptToHash(str: string) {
    return bcrypt.hashSync(str, 16);
  }
}